package com.stlm2.controller.pay;

import com.pingplusplus.exception.APIConnectionException;
import com.pingplusplus.exception.APIException;
import com.pingplusplus.exception.AuthenticationException;
import com.pingplusplus.exception.InvalidRequestException;
import com.pingplusplus.model.Charge;
import com.pingplusplus.util.WxpubOAuth;
import com.stlm2.core.WechatConfig;
import com.stlm2.dems.entity.FlowSource;
import com.stlm2.dems.pingxxpay.service.OrderPayService;
import com.stlm2.dems.entity.OrderState;
import com.stlm2.dems.entity.PayChannel;
import com.stlm2.dems.recharge.entity.Recharge;
import com.stlm2.dems.recharge.service.RechargeService;
import com.stlm2.dems.entity.User;
import com.stlm2.dems.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import util.PingPlusPlus;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;

import com.pingplusplus.Pingpp;
import com.pingplusplus.model.Event;
import com.pingplusplus.model.Webhooks;


@Controller
@RequestMapping("/pingxx")
public class PingxxPayController {

    private static Logger logger = LoggerFactory.getLogger(PingxxPayController.class);

    @Resource
    private PingPlusPlus pingxx;
    @Resource
    private UserService userService;
    @Resource
    private RechargeService rechargeService;
    @Resource
    private OrderPayService orderPayService;


    @ResponseBody
    @RequestMapping("/pay")
    public String PingxxPay(String companyCode,HttpServletRequest request, HttpServletResponse response,String phone, ModelMap model, String orderCode, String money, String open_id, String type, String token, Integer payChannelValue,String fluxId,String flux) throws APIException, AuthenticationException, InvalidRequestException, APIConnectionException {
        response.setHeader("Access-Control-Allow-Origin", "*");

        System.out.println("发起ping++支付");
        User user= userService.getByToken(token);

        if (user == null) {
            model.put("code", 0);
            model.put("msg", "用户未登陆");
            return new JSONObject(model).toString();
        }

        if (StringUtils.isBlank(orderCode)) {
            model.put("code", 0);
            model.put("msg", "订单id错误");
            return new JSONObject(model).toString();
        }

        PayChannel payChannel = null;
        if (payChannelValue != null) {
            payChannel = PayChannel.getByIntValue(payChannelValue);
        }

        if (payChannel == null) {
            model.put("code", 0);
            model.put("msg", "支付渠道错误");
            return new JSONObject(model).toString();
        }

        FlowSource fundsSource = FlowSource.getByIntValue(Integer.parseInt(orderCode.substring(0, 2)));
        Pingpp.apiKey = pingxx.getApiKey();
        String openid = open_id;

        if (payChannelValue == PayChannel.wx_pub.getIntValue()) {
            if (open_id == null || open_id.isEmpty()) {
                try {
                    String url = WxpubOAuth.createOauthUrlForCode(WechatConfig.appId, "http://www.hantangyd.com/weixinpub/weixinopenid?orderCode=" + orderCode + "&money=" + money + "&domain=" + request.getServerName() + "&type=" + type, false);
                    model.put("code", 10);
                    model.put("msg", "跳转到微信授权");
                    model.put("url", url);
                    return new JSONObject(model).toString();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        logger.info("openid:{} orderCode{}",openid,orderCode);

        String rootUrl="http://www.hantangyd.com";

        Charge charge = null;
        if (FlowSource.ChongZhi.equals(fundsSource)) {//充值
            //PurchaseOrder order = purchaseOrderService.getByCode(orderCode);
            //Recharge order=rechargeService.getByCode(orderCode);
            Recharge order=rechargeService.addRecharge(user.getId(),money,Integer.parseInt(fluxId),Integer.parseInt(flux),phone);
            if(order==null){
                model.put("code", 0);
                model.put("msg", "支付订单为null，请重试");
                return new JSONObject(model).toString();
            }

            if (order == null || !order.getUserId().equals(user.getId())) {
                model.put("code", 0);
                model.put("msg", "请求支付错误，请重试");
                return new JSONObject(model).toString();
            }
            if (!OrderState.Create.equals(order.getOrderState()) || order.getMoney() == null || order.getMoney().doubleValue() <= 0) {
                model.put("code", 0);
                model.put("msg", "订单" + order.getOrderState().toString() + "，不能支付");
                return new JSONObject(model).toString();
            }


            charge = orderPayService.createMoneyRechargeCharge(openid, payChannel, order, pingxx.getAppId(), getIP(request), rootUrl);

        }
        if (charge != null) {
            logger.info("/pingxx/pay_order_code:{} payChannel{}", orderCode, payChannelValue);
            return new JSONObject(charge).toString();
        } else {
            logger.error("/pingxx/pay_order_code:{} payChannel{}", orderCode, payChannelValue);
            model.put("code", 0);
            model.put("msg", "支付数据错误４");
            return new JSONObject(model).toString();
        }
    }

    private String getIP(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (!checkIP(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (!checkIP(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (!checkIP(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    private boolean checkIP(String ip) {
        return !(ip == null || ip.length() == 0 || "unkown".equalsIgnoreCase(ip)
                || ip.split(".").length != 4);
    }


/*    @ResponseBody
    @RequestMapping("/queryPay")
    public String queryCharge(String chargeId) {
        Pingpp.apiKey = pingxx.getApiKey();
        orderPayService.pingxxCheckPay(pingxx.getApiKey());
        return null;
    }*/


    @ResponseBody
    @RequestMapping("/webhooks/charge")
    public String Webhooks(String companyCode,HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        response.setStatus(302);
        try {
            request.setCharacterEncoding("UTF8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //获取头部所有信息
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
        }
        try {
            BufferedReader reader = request.getReader();
            StringBuffer buffer = new StringBuffer();
            String string;
            while ((string = reader.readLine()) != null) {
                buffer.append(string);
            }
            reader.close();
            // 解析异步通知数据
            Event event = Webhooks.eventParse(buffer.toString());
            if (event == null) {
                model.put("code", 0);
                model.put("msg", "支付数据错误１");
                return new JSONObject(model).toString();
            }

            boolean paid = orderPayService.webhooksCharge(event);
            if (paid) {
                response.setStatus(200);
                model.put("code", 1);
                model.put("msg", "支付成功");
                return new JSONObject(model).toString();
            } else {
                model.put("code", 0);
                model.put("msg", "支付数据错误２");
                return new JSONObject(model).toString();
            }

        } catch (IOException e) {
            model.put("code", 0);
            model.put("msg", "支付数据错误３");
            return new JSONObject(model).toString();
        }
    }
  //测试服务器回调地址

}
